package cn.mrcode.fd.blog.services.impl;

import cn.mrcode.fd.blog.dao.mapper.CategoryMapMapper;
import cn.mrcode.fd.blog.dao.mapper.CategoryMapper;
import cn.mrcode.fd.blog.dao.mappercu.CategoryCuMapper;
import cn.mrcode.fd.blog.dao.mappercu.CategoryMapCuMapper;
import cn.mrcode.fd.blog.entity.Category;
import cn.mrcode.fd.blog.entity.CategoryMapKey;
import cn.mrcode.fd.blog.services.ICategoryService;
import cn.mrcode.fd.utils.UUID;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * 文章分类列表服务
 *
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/1/1 16:08
 */
@Service
@Transactional(readOnly = true)
public class CategoryServiceImpl implements ICategoryService {
    private Logger log =  LoggerFactory.getLogger(getClass());
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryCuMapper categoryCuMapper;
    @Autowired
    private CategoryMapMapper categoryMapMapper;
    @Autowired
    private CategoryMapCuMapper categoryMapCuMapper;

    @Override
    @Transactional
    public void handerCategory(String articleId, String userAccount, String categoryNames) {
        /**
         *  1. 删除该文章的分类引用
         *  2. 查询所有的分类
         *  3. 提交的列表名称 与 数据库中的分类列表对比，存在的直接添加索引，不存在的先添加分类
         */
        this.delAllRefBy(articleId);
        if (StringUtils.isNotBlank(categoryNames)) {
            List<Category> categories = findAllByAccount(userAccount);
            HashMap<String, Category> catMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(categories)) {
                for (Category category : categories) {
                    catMap.put(category.getName(), category);
                }
            }

            String[] cats = categoryNames.split(",");
            for (String catName : cats) {
                Category category = catMap.get(catName);
                if (category == null) {
                    category = new Category();
                    category.setId(UUID.uuid());
                    category.setNum(1);
                    category.setName(catName);
                    category.setUserAccount(userAccount);
                    categoryMapper.insertSelective(category);
                }

                CategoryMapKey record = new CategoryMapKey();
                record.setArticleId(articleId);
                record.setCategoryId(category.getId());
                categoryMapMapper.insert(record);
            }
            categoryMapCuMapper.incNum(articleId,1);
        }
    }

    @Override
    @Transactional
    public void delRef(String articleId) {
        this.delAllRefBy(articleId);
    }

    @Override
    public List<Category> findAllByAccount(String userAccount) {
        Category category = new Category();
        category.setUserAccount(userAccount);

        List<Category> result = categoryCuMapper.selectSelective(category);
        return result;
    }

    @Override
    public List<Category> findArticleCat(String articleId) {
        List<Category> categories = categoryCuMapper.selectArticleCat(articleId);
        return categories;
    }

    /**
     *   1. 对该文章引用的所有分类 引用数量减少1
     *   2. 删除该文章id的所有引用分类
     * @param articleId
     */
    public int delAllRefBy(String articleId) {
        CategoryMapKey selective = new CategoryMapKey();
        selective.setArticleId(articleId);
        int i = categoryMapCuMapper.incNum(articleId, -1);
        int i1 = categoryMapCuMapper.deleteSelective(selective);
        return i;
    }

    @Override
    @Transactional
    public synchronized void recountAllNum(){
        int upLine = categoryCuMapper.setNum(null,0);
        log.warn("重置所有分类列表的引用数量，影响行数={}",upLine);
        List<CategoryMapKey> categoryMapKeys = categoryMapCuMapper.selectSelective(null);
        for (CategoryMapKey categoryMapKey : categoryMapKeys) {
            String articleId = categoryMapKey.getArticleId();
            String categoryId = categoryMapKey.getCategoryId();
            categoryCuMapper.incNum(categoryId,1);
        }
    }

    @Override
    @Transactional
    public void catByArtId(String artId, String catId, boolean isAdd) throws RuntimeException{
        CategoryMapKey selective = new CategoryMapKey();
        selective.setArticleId(artId);
        selective.setCategoryId(catId);

        List<CategoryMapKey> list = categoryMapCuMapper.selectSelective(selective);
        if(CollectionUtils.isEmpty(list)){
            categoryMapMapper.insert(selective);
            categoryCuMapper.incNum(catId,1);
        }else{
            categoryMapMapper.deleteByPrimaryKey(selective);
            categoryCuMapper.incNum(catId,-1);
        }
    }
}
